﻿Imports ecomLibrary
Imports utilitiesLibrary
Imports System.Net.Mail

Public Class checkout
    Inherits System.Web.UI.Page

    Dim shopCart As cart
    Dim userID As String
    Dim objStores As New Stores
    Dim objDB As DBConnect

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        shopCart = Session("cart")
        userID = Session("login")
        objDB = Session("db")

        If userID Is Nothing Then
            Response.Redirect("http://cis-iis2.temple.edu/Fall2011/434202/TermProjectCL/Login/storefront.aspx")
            Exit Sub
        End If

        If Not IsPostBack Then
            displayUsername()
            gvCart.DataSource = shopCart.cart
            gvCart.DataBind()
            computeSaleTotals()
        End If

    End Sub

    Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSubmit.Click
        Dim objProd As product
        Dim storeNo As Object
        Dim prodNo As Object
        Dim qtyPurchased As Object
        Dim pxy As Object
        Dim isInStock As Integer
        Dim totalCurrent As Decimal = 0
        Dim sql As String
        Dim oldTotalSale As Decimal
        Dim sw As System.IO.StringWriter = New System.IO.StringWriter
        Dim hw As System.Web.UI.HtmlTextWriter = New System.Web.UI.HtmlTextWriter(sw)

        If shopCart.cart.Count <= 0 Then
            lblInfo.Visible = True
            lblInfo.Text = "Add items to your cart before attempting to checkout."
            Exit Sub
        End If

        For i As Integer = 0 To (shopCart.cart.Count - 1)
            Try
                objProd = shopCart.cart.Item(i)
                prodNo = objProd.ProdNo
                storeNo = CType(objProd.storeID, String)
                pxy = objStores.getPxy(storeNo)
                qtyPurchased = objProd.quantityOrd
                isInStock = pxy.updateQOH(prodNo, qtyPurchased)

                If isInStock = 0 Then
                    lblInfo.Visible = True
                    lblInfo.Text = "product: " & objProd.Description & " is currently out of stock. Please remove it from your cart and try to order again."
                    Exit Sub
                End If

                totalCurrent += objProd.total

            Catch ex As Exception
                lblInfo.Visible = True
                lblInfo.Text = "Error processing order."
                Exit Sub
            End Try

        Next

        Try
            sql = "SELECT TotalDollarSales FROM mall_customer WHERE LoginID='" & userID & "'"
            objDB.getDataSet(sql)
            oldTotalSale = objDB.getField("TotalDollarSales", 0)
            totalCurrent += oldTotalSale
        Catch ex As Exception
            lblInfo.Visible = True
            lblInfo.Text = "Uable to read TotalDollarSales field from database."
        End Try

        Try
            sql = "UPDATE mall_customer SET TotalDollarSales=" & totalCurrent & " WHERE LoginID='" & userID & "'"
            objDB.doUpdate(sql)
        Catch ex As Exception
            lblInfo.Visible = True
            lblInfo.Text = "unable to update customer sales"
        End Try

        lblInfo.Visible = True

        'do email stuffs
        'Dim name As String
        'sql = "SELECT * FROM mall_customer WHERE LoginID='" & userID & "'"
        'objDB.getDataSet(sql)
        'name = objDB.getField("CustName", 0)
        'gvCart.Columns(0).Visible = False
        'gvCart.Columns(5).Visible = False
        'gvCart.Columns(1).FooterText = "Totals"
        'gvCart.RenderControl(hw)
        'Dim objSmtp As New SmtpClient("smtp.temple.edu")
        'Dim mailTo As New MailAddress(userID)
        'Dim mailFrom As New MailAddress("no-reply@holyemailbatman.com")
        'Dim objMail As New MailMessage(mailFrom, mailTo)
        'objMail.Subject = "Thanks for your order!"
        'objMail.IsBodyHtml = True
        'Dim body As String = "Thank you " & name & ", for spending a bunch of money on crap you don't need! We are going to go buy drugs with it now.  " & "<BR><BR>"
        'body += sw.ToString & "<BR><BR>"
        'body += "Yours Truly, <BR> Sexy Mall Time Fun Order Stuff Zone"
        'objMail.Body = body
        'objSmtp.Send(objMail)
        lblInfo.Visible = True
        lblInfo.Text = "Order complete. Confirmation email has been sent to: " & userID

        shopCart.emptyCart()
        Session("cart") = shopCart
        gvCart.DataBind()
        btnContShop.Text = "Another Order!"
        btnUpdate.Visible = False
        btnDelete.Visible = False
        btnSubmit.Visible = False
        btnEmptyCart.Visible = False

    End Sub

    Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
    End Sub

    Protected Sub btnEmptyCart_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnEmptyCart.Click
        shopCart.emptyCart()
        Response.Redirect("checkout.aspx")
    End Sub

    Protected Sub displayUsername()
        Dim userSplit As Array
        userSplit = userID.Split("@")
        userID = userSplit(0)
        userID = userID & "!"
        lblUser.Text = userID
    End Sub

    Protected Sub btnLogout_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnLogout.Click
        Dim objSer As New Serialize
        Dim objCart As cart = Session("cart")
        Dim LoginID As String = objCart.LoginID

        objSer.WriteCartS(objCart, LoginID)

        Response.Redirect("../Login/storefront.aspx")
    End Sub


    Protected Sub btnContShop_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnContShop.Click
        Session("cart") = shopCart
        Response.Redirect("store.aspx")
    End Sub

    Protected Sub btnUpdate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnUpdate.Click
        Dim Cbox As New CheckBox
        Dim Tbox As New TextBox
        Dim prod As New product
        Dim qty As New Integer



        For i As Integer = 0 To gvCart.Rows.Count - 1
            Cbox = CType(gvCart.Rows(i).FindControl("chkSelProd"), CheckBox)
            If Cbox.Checked Then
                Tbox = CType(gvCart.Rows(i).FindControl("txtUpdQty"), TextBox)
                Try
                    qty = CType(Tbox.Text, Integer)
                    prod = shopCart.cart.Item(i)
                    prod.total = CType(prod.Price * qty, Decimal)
                    shopCart.changeQuantOrdered(prod, Tbox.Text)
                Catch ex As Exception
                    lblInfo.Visible = True
                    lblInfo.Text = "Please enter an integer into any item quantity you wish to update"
                End Try
            End If
        Next
        Session("cart") = shopCart
        Response.Redirect("checkout.aspx")
    End Sub

    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnDelete.Click
        Dim Cbox As New CheckBox
        Dim Tbox As New TextBox
        Dim prod As New product
        Dim index As Integer = 0
        Dim cartCount As Integer


        cartCount = shopCart.cart.Count - 1


        For i As Integer = cartCount To 0 Step -1
            Cbox = CType(gvCart.Rows(i).FindControl("chkSelProd"), CheckBox)
            If Cbox.Checked Then
                Try
                    prod = shopCart.cart.Item(i)
                    shopCart.deleteProduct(prod)
                Catch ex As Exception
                End Try
            End If
        Next

        Session("cart") = shopCart
        Response.Redirect("checkout.aspx")
    End Sub

    Protected Sub computeSaleTotals()
        Dim totalQty As Integer
        Dim totalSale As Decimal

        For x As Integer = 0 To (gvCart.Rows.Count - 1)
            totalQty = CType(gvCart.Rows(x).Cells(3).Text, Integer) + totalQty
            totalSale = CType(gvCart.Rows(x).Cells(4).Text, Decimal) + totalSale
        Next

        gvCart.ShowFooter = True
        gvCart.Columns(0).FooterText = "Totals"
        gvCart.Columns(3).FooterText = totalQty.ToString
        gvCart.Columns(3).FooterStyle.HorizontalAlign = HorizontalAlign.Center

        gvCart.Columns(4).FooterText = totalSale.ToString
        gvCart.Columns(4).FooterStyle.HorizontalAlign = HorizontalAlign.Center

        gvCart.DataSource = shopCart.cart
        gvCart.DataBind()

    End Sub

End Class